import { clickElement } from '../helper'
import { state } from '../../common'
import { zoomRender } from '../zoom'

export function keyboardZoomEvents() {
  // 快捷键
  window.addEventListener('keydown', event => {
    // control or command key
    if (!event.ctrlKey && !event.metaKey) return
    switch (event.which) {
      case 187:
        if (state.zoom < 4) clickElement(document.querySelector('.zoom-out'))
        event.preventDefault()
        return false
      case 189:
        if (state.zoom > 0.25) clickElement(document.querySelector('.zoom-in'))
        event.preventDefault()
        return false
      case 48:
        zoomRender(1)
        event.preventDefault()
        return false
      default:
        break
    }
  })

  //判断鼠标滚轮滚动方向
  if (window.addEventListener) {
    //FF,火狐浏览器会识别该方法
    window.addEventListener('DOMMouseScroll', wheel, { passive: false })
  }

  // window.onmousewheel = document.onmousewheel = wheel //IE/Opera/Chrome/Safari
  window.addEventListener('mousewheel', wheel, { passive: false })

  //统一处理滚轮滚动事件
  function wheel(event) {
    var delta = 0
    if (!event) event = window.event
    if (event.wheelDelta) {
      //IE、chrome浏览器使用的是wheelDelta，并且值为“正负120”
      delta = event.wheelDelta / 120
      // if (window.opera) delta = -delta //因为IE、chrome等向下滚动是负值，FF是正值，为了处理一致性，在此取反处理
    } else if (event.detail) {
      //FF浏览器使用的是detail,其值为“正负3”
      delta = -event.detail / 3
    }
    if (delta) handle(event, delta)
  }

  //上下滚动时的具体处理函数
  function handle(event, delta) {
    if (event.ctrlKey) {
      if (delta < 0) {
        // 向下滚动
        clickElement(document.querySelector('.zoom-in'))
      } else {
        // 向上滚动
        clickElement(document.querySelector('.zoom-out'))
      }

      event.returnValue = false
    }
  }
}
